/**
 * 订单管理服务模块
 *
 * 处理订单相关的数据操作逻辑
 */
const { Order, OrderItem, Goods, User, UserAddress } = require('../models');
const { Op } = require('sequelize');
const CustomError = require('../utils/customError');

// 订单状态定义
const ORDER_STATUS = {
  UNPAID: 1,      // 待付款
  PAID: 2,        // 已付款
  DELIVERING: 3,  // 配送中
  DELIVERED: 4,   // 已配送
  REFUNDING: 5,   // 退货中
  REFUNDED: 6     // 已退款
};

// 订单状态流转规则
const VALID_TRANSITIONS = {
  [ORDER_STATUS.UNPAID]: [ORDER_STATUS.PAID, ORDER_STATUS.REFUNDED],       // 待付款 → 已付款/已退款
  [ORDER_STATUS.PAID]: [ORDER_STATUS.DELIVERING, ORDER_STATUS.REFUNDING],  // 已付款 → 配送中/退货中
  [ORDER_STATUS.DELIVERING]: [ORDER_STATUS.DELIVERED],                     // 配送中 → 已配送
  [ORDER_STATUS.DELIVERED]: [ORDER_STATUS.REFUNDING],                     // 已配送 → 退货中
  [ORDER_STATUS.REFUNDING]: [ORDER_STATUS.REFUNDED],                      // 退货中 → 已退款
  [ORDER_STATUS.REFUNDED]: []                                             // 已退款 → 无
};

class OrderService {
  /**
   * 生成唯一订单号
   * @returns {string} 订单号
   */
  static generateOrderNo() {
    const timestamp = new Date().getTime();
    const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
    return `ORD${timestamp}${random}`;
  }

  /**
   * 验证订单状态流转是否合法
   * @param {number} currentStatus 当前状态
   * @param {number} newStatus 新状态
   * @returns {boolean} 是否合法
   */
  static validateStatusTransition(currentStatus, newStatus) {
    return VALID_TRANSITIONS[currentStatus]?.includes(newStatus) || false;
  }

  /**
   * 创建订单
   * @param {Object} orderData 订单数据
   * @returns {Promise<Object>} 创建的订单
   */
  static async createOrder(orderData) {
    const { userId, orderDetailList, totalAmount, totalNum, userAddressId, paymentWay } = orderData;

    // 验证用户地址是否存在
    const userAddress = await UserAddress.findOne({
      where: {
        id: userAddressId,
        userId
      }
    });

    if (!userAddress) {
      throw new CustomError('收货地址不存在', 404);
    }

    // 生成订单号
    const orderNo = this.generateOrderNo();

    // 使用事务创建订单和订单明细
    const transaction = await Order.sequelize.transaction();

    try {
      // 创建订单主表
      const order = await Order.create({
        orderNo,
        userId,
        totalAmount,
        status: ORDER_STATUS.UNPAID,
        receiverName: userAddress.receiverName,
        receiverPhone: userAddress.receiverPhone,
        province: userAddress.provinceName,
        city: userAddress.cityName,
        district: userAddress.districtName,
        detailAddress: userAddress.detail,
        orderType: 1, // 商品订单
        expectedDeliveryDate: orderData.expectedDeliveryDate,
        remark: orderData.remark
      }, { transaction });

      // 创建订单明细
      const orderItems = orderDetailList.map(item => ({
        orderId: order.id,
        goodsId: item.goodsId,
        quantity: item.goodsCount,
        price: item.goodsPrice,
        blessing: item.blessing
      }));

      await OrderItem.bulkCreate(orderItems, { transaction });

      // 提交事务
      await transaction.commit();

      return {
        orderId: order.id,
        orderNo: order.orderNo,
        totalAmount: order.totalAmount,
        paymentWay,
        orderStatus: ORDER_STATUS.UNPAID
      };
    } catch (error) {
      // 回滚事务
      await transaction.rollback();
      throw error;
    }
  }

  /**
   * 获取订单详情
   * @param {number} orderNo 订单号
   * @param {number} userId 用户ID
   * @returns {Promise<Object>} 订单详情
   */
  static async getOrderDetail(orderNo, userId) {
    const order = await Order.findOne({
      where: {
        orderNo,
        userId
      },
      include: [
        {
          model: OrderItem,
          as: 'orderItems',
          include: [
            {
              model: Goods,
              as: 'goods',
              attributes: ['id', 'name', 'mainImgUrl']
            }
          ]
        }
      ]
    });

    if (!order) {
      throw new CustomError('订单不存在', 404);
    }

    return order;
  }

  /**
   * 获取订单列表
   * @param {number} page 页码
   * @param {number} limit 每页数量
   * @param {number} userId 用户ID
   * @param {number} orderStatus 订单状态（可选）
   * @returns {Promise<Object>} 订单列表
   */
  static async getOrderList(page, limit, userId, orderStatus) {
    const offset = (page - 1) * limit;
    const whereClause = { userId };

    // 订单状态筛选
    if (orderStatus) {
      whereClause.status = orderStatus;
    }

    const { count, rows } = await Order.findAndCountAll({
      where: whereClause,
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['created_at', 'DESC']],
      include: [
        {
          model: OrderItem,
          as: 'orderItems',
          include: [
            {
              model: Goods,
              as: 'goods',
              attributes: ['id', 'name', 'mainImgUrl']
            }
          ]
        }
      ]
    });

    return {
      total: count,
      records: rows,
      page: parseInt(page),
      limit: parseInt(limit)
    };
  }

  /**
   * 获取立即购买商品信息
   * @param {number} goodsId 商品ID
   * @param {number} userId 用户ID
   * @param {string} blessing 祝福语（可选）
   * @returns {Promise<Object>} 立即购买商品信息
   */
  static async getImmediatePurchaseInfo(goodsId, userId, blessing) {
    // 获取商品信息
    const goods = await Goods.findOne({
      where: {
        id: goodsId,
        onSale: 1
      }
    });

    if (!goods) {
      throw new CustomError('商品不存在或已下架', 404);
    }

    // 获取用户默认地址
    const userAddress = await UserAddress.findOne({
      where: {
        userId,
        isDefault: 1
      }
    });

    return {
      userAddress: userAddress || null,
      goods: {
        id: goods.id,
        name: goods.name,
        price: goods.price,
        imageUrl: goods.mainImgUrl,
        stock: goods.stock
      },
      blessing
    };
  }

  /**
   * 更新订单状态
   * @param {number} orderNo 订单号
   * @param {number} userId 用户ID
   * @param {number} newStatus 新状态
   * @returns {Promise<Object>} 更新结果
   */
  static async updateOrderStatus(orderNo, userId, newStatus) {
    // 获取当前订单
    const order = await Order.findOne({
      where: {
        orderNo,
        userId
      }
    });

    if (!order) {
      throw new CustomError('订单不存在', 404);
    }

    // 验证状态流转是否合法
    if (!this.validateStatusTransition(order.status, newStatus)) {
      throw new CustomError('不允许的状态流转', 400);
    }

    // 更新订单状态
    await order.update({ status: newStatus });

    return {
      orderNo: order.orderNo,
      orderStatus: newStatus,
      updatedAt: order.updatedAt
    };
  }

  /**
   * 支付订单
   * @param {number} orderNo 订单号
   * @param {number} userId 用户ID
   * @returns {Promise<Object>} 支付结果
   */
  static async payOrder(orderNo, userId) {
    return this.updateOrderStatus(orderNo, userId, ORDER_STATUS.PAID);
  }

  /**
   * 发货
   * @param {number} orderNo 订单号
   * @param {number} userId 用户ID
   * @returns {Promise<Object>} 发货结果
   */
  static async shipOrder(orderNo, userId) {
    return this.updateOrderStatus(orderNo, userId, ORDER_STATUS.DELIVERING);
  }

  /**
   * 确认收货
   * @param {number} orderNo 订单号
   * @param {number} userId 用户ID
   * @returns {Promise<Object>} 确认收货结果
   */
  static async deliverOrder(orderNo, userId) {
    return this.updateOrderStatus(orderNo, userId, ORDER_STATUS.DELIVERED);
  }

  /**
   * 申请退款
   * @param {number} orderNo 订单号
   * @param {number} userId 用户ID
   * @returns {Promise<Object>} 申请退款结果
   */
  static async initiateRefund(orderNo, userId) {
    return this.updateOrderStatus(orderNo, userId, ORDER_STATUS.REFUNDING);
  }

  /**
   * 完成退款
   * @param {number} orderNo 订单号
   * @param {number} userId 用户ID
   * @returns {Promise<Object>} 完成退款结果
   */
  static async completeRefund(orderNo, userId) {
    return this.updateOrderStatus(orderNo, userId, ORDER_STATUS.REFUNDED);
  }
}

module.exports = OrderService;